package content

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"path"
	"time"
	"woo-server/coms/structs"
	"woo-server/models/api"
	"woo-server/models/db/content"
)

// 结构
type UploadFileService struct {
	*structs.Common
}

// 初始化
func NewUploadFileService(com *structs.Common) *UploadFileService {
	return &UploadFileService{com}
}

// 上传单图片
func (f *UploadFileService) UploadFile(context *gin.Context) *api.ResultEntity {
	// 获取不包含目录的文件名
	//filenameall := path.Base(file.Filename)
	// 文件前缀 可以使用切片的方式获取：
	//fileprefix := filenameall[0 : len(filenameall)-len(filesuffix)]
	//fileprefix, err := strings.TrimSuffix(filenameall, filesuffix)

	// 单文件
	file, fileErr := context.FormFile("file")
	GroupId := structs.SetInt(context.PostForm("GroupId"))
	fmt.Println(GroupId)
	if fileErr != nil {
		return api.Error(fileErr.Error())
	}
	fmt.Println("uploadSize: ", file.Size)
	// 保存目录
	filePath := "/static/images"
	// 保存名称
	fileName := time.Now().Format("20060102150405")
	// 文件后缀
	fileSuffix := path.Ext(file.Filename)
	// DS 系统/杠
	DS := "/"
	// 完整保存路径
	dist := filePath + DS + "public" + DS + fileName + fileSuffix
	// 上传文件至指定目录
	err := context.SaveUploadedFile(file, "."+dist)
	if err != nil {
		return api.Error(err.Error())
	}
	fileModel := content.NewUploadFile(f.Common)
	fileModel.SetCreateInfo(f.Claim.UserId)
	fileModel.FileName = dist
	fileModel.Extension = fileSuffix
	fileModel.GroupId = uint64(GroupId)
	fileModel.Storage = "local"
	fileModel.FileSize = file.Size
	fileModel.FileType = "image"
	resultErr := fileModel.Create()
	if resultErr != nil {
		return api.Error(resultErr.Error())
	}
	//result := map[string]interface{}{"Name": dist, "Group": "public", "Suffix": fileSuffix, "FilePath": filePath, "FileId": fileModel.FileId}
	fmt.Println(resultErr, fileModel)
	return api.SuccessToJson(fileModel, "success")
}

// 获取所有菜单
// @param isHidden 是否显示
// return treeList 树状菜单 , list 非树状
func (f *UploadFileService) GetFileList(context *gin.Context) *api.ResultEntity {
	fileModel := content.NewUploadFile(f.Common)
	page := structs.SetInt(context.Query("page"))
	pageSize := structs.SetInt(context.Query("pageSize"))
	search := context.Query("search")
	list, total := fileModel.GetListAndTotal(structs.SetInt(search), page, pageSize)
	result := map[string]interface{}{"list": list, "total": total}
	return api.SuccessToJson(result, "success")
}
